<template>
  <el-dialog
    :title="formType === 'add' ? '新增用户' : '编辑用户'"
    v-model="dialogVisible"
    width="650px"
    @close="handleClose"
    top="5vh"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-position="right"
      class="user-form"
    >
      <div class="form-container">
        <div class="form-main">
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model="form.userName"
              placeholder="请输入用户名"
              clearable
            />
          </el-form-item>

          <el-form-item label="姓名" prop="fullName">
            <el-input
              v-model="form.fullName"
              placeholder="请输入姓名"
              clearable
            />
          </el-form-item>

          <el-form-item label="密码" prop="password" v-if="formType === 'add'">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              show-password
            />
          </el-form-item>

          <el-form-item label="手机号码" prop="phoneNumber">
            <el-input
              v-model="form.phoneNumber"
              placeholder="请输入手机号码"
              clearable
            />
          </el-form-item>

          <el-form-item label="头像URL" prop="avatarAddress">
            <el-input
              v-model="form.avatarAddress"
              placeholder="请输入头像URL地址"
              clearable
            />
          </el-form-item>
        </div>

        <div class="form-avatar">
          <div class="avatar-container">
            <p class="avatar-title">头像预览</p>
            <el-avatar
              :size="120"
              :src="form.avatarAddress"
              v-if="form.avatarAddress"
            />
            <el-avatar :size="120" :icon="UserFilled" v-else />
          </div>
        </div>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting"
          >提交</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from "vue";
import { ElMessage } from "element-plus";
import { UserFilled } from "@element-plus/icons-vue";
import userApi from "@/api/user";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  formType: {
    type: String,
    default: "add", // 'add' 或 'edit'
  },
  userData: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(["update:modelValue", "submit-success"]);

// 对话框可见性
const dialogVisible = ref(props.modelValue);

// 表单引用，用于表单验证
const formRef = ref(null);

// 提交状态
const submitting = ref(false);

// 表单数据
const form = reactive({
  id: undefined,
  userName: "",
  fullName: "",
  password: "",
  phoneNumber: "",
  avatarAddress: "",
});

// 表单验证规则
const rules = {
  userName: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  fullName: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  phoneNumber: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  avatarAddress: [
    { required: false },
    {
      pattern: /^(https?:\/\/|\/)[^\s]+$/,
      message: "请输入有效的URL地址",
      trigger: "blur",
    },
  ],
};

// 监听modelValue变化，同步对话框状态
watch(
  () => props.modelValue,
  (val) => {
    dialogVisible.value = val;
  }
);

// 监听dialogVisible变化，同步到父组件
watch(dialogVisible, (val) => {
  emit("update:modelValue", val);
});

// 监听userData变化，更新表单数据
watch(
  () => props.userData,
  (val) => {
    if (val && Object.keys(val).length > 0) {
      Object.assign(form, val);
    }
  },
  { immediate: true, deep: true }
);

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }

  Object.keys(form).forEach((key) => {
    if (key !== "id") {
      form[key] = "";
    } else {
      form[key] = undefined;
    }
  });
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid, fields) => {
    if (!valid) {
      console.error("表单验证失败:", fields);
      return;
    }

    submitting.value = true;
    try {
      const apiMethod =
        props.formType === "add" ? userApi.createUser : userApi.updateUser;

      await apiMethod(form);

      ElMessage.success(props.formType === "add" ? "添加成功" : "更新成功");
      emit("submit-success");
      handleClose();
    } catch (error) {
      console.error(
        props.formType === "add" ? "添加用户失败:" : "更新用户失败:",
        error
      );
      ElMessage.error(
        props.formType === "add" ? "添加用户失败" : "更新用户失败"
      );
    } finally {
      submitting.value = false;
    }
  });
};
</script>

<style scoped>
.user-form {
  padding: 20px 0;
}

.form-container {
  display: flex;
  gap: 30px;
}

.form-main {
  flex: 1;
}

.form-avatar {
  width: 180px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.avatar-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 15px;
}

.avatar-preview {
  margin-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
